package io.zhengsh.jvm.ref;

import java.lang.ref.SoftReference;

/**
 * 软引用测试
 */
public class SoftReferenceDemo {

    // 系统内存 充足 的时候它 不会 被回收
    public static void softRefMemoryEnough() {
        Object obj = new Object();
        SoftReference<Object> softReference = new SoftReference<>(obj);
        System.out.println(obj);
        System.out.println(softReference.get());

        obj = null;
        System.gc();

        System.out.println(obj);
        System.out.println(softReference.get());

//        输出结果：
//        java.lang.Object@dcf3e99
//        java.lang.Object@dcf3e99
//        null
//        java.lang.Object@dcf3e99

    }

    // VM ARGS: -Xms5mb -Xmx5mb -XX:+PrintGCDetails
    public static void softRefMemoryNotEnough() {
        Object obj = new Object();
        SoftReference<Object> softReference = new SoftReference<>(obj);
        System.out.println(obj);
        System.out.println(softReference.get());

        obj = null;
        System.gc();

        try {
            byte[] bytes = new byte[30 * 1024 * 1024];
        }catch (Throwable t) {
            t.printStackTrace();
        } finally {
            System.out.println(obj);
            System.out.println(softReference.get());
        }

    }

    public static void main(String[] args) {
        softRefMemoryEnough();
        softRefMemoryNotEnough();
    }
}

